﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Fsb.Utility;
using VideoCache.Server.BLL;
using VideoCache.Server.Model;
using VideoCache.Server.MVCWeb.Areas.Api.Models;
using VideoCache.Security;

namespace VideoCache.Server.MVCWeb.Areas.Api.Controllers
{
    public class AuthenticationController : Controller
    {
        public ActionResult Authenticate(AuthenticationModel model)
        {
            AuthenticationResultModel result = new AuthenticationResultModel();

            if (ModelState.IsValid)
            {
                // 1. 验证商户编号和商户密码
                if (this.VerifyNetbar(model.CompanyId, model.Password))
                {
                    NetbarInfo info = NetbarBLL.Find(model.CompanyId);
                    if (info != null)
                    {
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.CompanyId.ToString(), DateTime.Now, DateTime.Now.AddHours(12), true, JsonUtility.Json(info));
                        string encrptyTicket = FormsAuthentication.Encrypt(ticket);

                        HttpCookie cookie = new HttpCookie(AuthenticationModel.CookieName, encrptyTicket);
                        cookie.Path = "/api";
                        Response.Cookies.Add(cookie);
                        result.Authenticated = true;
                    }
                    else
                    {
                        result.Authenticated = false;
                        result.Message = "指定的商户编号不存在。";
                    }
                }
                else
                {
                    result.Authenticated = false;
                    result.Message = "商户编号或密码错误。";
                }
            }

            SecurityResponseModel responseModel = new SecurityResponseModel(result);

            return Json(responseModel);
        }

        private bool VerifyNetbar(int id, string password)
        {
            NetbarInfo info = NetbarBLL.Find(id);

            if (info == null) return false;

            if (info.Password == password)
            {
                return true;
            }

            return false;
        }
    }
}